package org.jeese.modules.sys.service.impl;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.jeese.modules.sys.dao.SysMenuDao;
import org.jeese.modules.sys.dao.SysRoleDao;
import org.jeese.modules.sys.dao.SysUserDao;
import org.jeese.modules.sys.entity.SysUser;
import org.jeese.modules.sys.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {
	@Autowired
	private SysUserDao userDao;
	@Autowired
	private SysMenuDao menuDao;
	@Autowired
	private SysRoleDao roleDao;

	@Override
	public SysUser getUserById(Long userId) {
		return userDao.getUserById(userId);
	}
	
	@Override
	public Set<String> getAdminRoles() {
		List<String> roles = roleDao.getAdminRoles();
		Set<String> rolesSet = new HashSet<>();
		for(String role : roles) {
			if(StringUtils.isNotBlank(role)) {
				rolesSet.addAll(Arrays.asList(role.trim().split(",")));
			}
		}
		return rolesSet;
	}

	@Override
	public Set<String> getAdminPermsSet() {
		List<String> perms = menuDao.getAdminPerms();
		Set<String> permsSet = new HashSet<>();
		for(String perm : perms) {
			if(StringUtils.isNotBlank(perm)) {
				permsSet.addAll(Arrays.asList(perm.trim().split(",")));
			}
		}
		return permsSet;
	}

	@Override
	public Set<String> getUserRoles(Long userId) {
		List<String> roles = roleDao.getUserRoles(userId);
		Set<String> rolesSet = new HashSet<>();
		for(String role : roles) {
			if(StringUtils.isNotBlank(role)) {
				rolesSet.addAll(Arrays.asList(role.trim().split(",")));
			}
		}
		return rolesSet;
	}

	@Override
	public Set<String> getUserPermsSet(Long userId) {
		List<String> perms = menuDao.getUserPerms(userId);
		Set<String> permsSet = new HashSet<>();
		for(String perm : perms) {
			if(StringUtils.isNotBlank(perm)) {
				permsSet.addAll(Arrays.asList(perm.trim().split(",")));
			}
		}
		return permsSet;
	}

	@Override
	public SysUser getByName(String name) {
		return userDao.getByName(name);
	}

	@Override
	public SysUser getByAccount(String account) {
		return userDao.getByAccount(account);
	}

	@Override
	public int editUserLoginInfo(Long userId, String ip) {
		return userDao.editUserLoginInfo(userId, ip);
	}

}
